//
//  ForgetViewController.m
//  YCVillageDoctor
//
//  Created by Mac on 2017/6/7.
//  Copyright © 2017年 zhangxiaoliang. All rights reserved.
//

#import "ForgetViewController.h"
#import "PopView.h"
#import "YCTabbarViewController.h"
#import "YCSSKeychain.h"
#import "ApplyMemberViewController.h"


@interface ForgetViewController ()
{
    int  _timeTick;
    BOOL _isregist;
}
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property (weak, nonatomic) IBOutlet UIButton *submitBtn;

@property (weak, nonatomic) IBOutlet UIView *userview;
@property (weak, nonatomic) IBOutlet UIView *codeview;
@property (weak, nonatomic) IBOutlet UIView *pwdView;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextfield;

@property (weak, nonatomic) IBOutlet UITextField *codeTextfield;
@property (nonatomic, strong) PopView *popView;

@property (weak, nonatomic) IBOutlet UITextField *passworldTextfield;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *forgetHight;

@property (weak, nonatomic) IBOutlet UIButton *CodeBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *marginHeight;
//@property (nonatomic, strong) PopView *popView;
//是否注册过
@property (assign,nonatomic)BOOL isregist;

//时间
@property (strong ,nonatomic)NSTimer *timer;

//保存验证码
@property (strong ,nonatomic)NSString *mgsCode;

/**
 *  保存验证码是否验证通过
 */
@property (nonatomic,assign)BOOL iscode;



//短息语音切换的参数
@property (nonatomic ,strong)NSString *codeType;

//是否短信和语音切换
@property (nonatomic,assign)BOOL  swithType;

- (IBAction)resetClick:(id)sender;

- (IBAction)backClick:(id)sender;
- (IBAction)codeClick:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *topImageView;

@end

@implementation ForgetViewController


/** 初始化弹出的View 返回值popView */
- (PopView *)createPopView {
    
    if (!_popView) {
        _popView = [PopView popView];
        [_popView setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.3]];
        _popView.titleLabel.text=@"恭喜你注册成功！";
        _popView.delegate = self;
        
        [self.view addSubview:_popView];
        [self viewShowAnimation];
    }
    return _popView;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //语音短信切换初始化
    self.codeType =@"0";
    self.swithType = NO;
    //self.CodeBtn.uxy_acceptEventInterval = 20;
    
    [[UITextField appearance] setTintColor:[UIColor colorWithHexString:@"CCCCCC"]];
    self.phoneTextfield.clearButtonMode =UITextFieldViewModeAlways;
    self.codeTextfield.clearButtonMode =UITextFieldViewModeAlways;
    self.codeTextfield.keyboardType = UIKeyboardTypeNumberPad;
    
    self.passworldTextfield.clearButtonMode =UITextFieldViewModeAlways;
    self.submitBtn.backgroundColor = login_BackgroundColor;
    self.submitBtn.layer.masksToBounds = YES;
    self.submitBtn.layer.cornerRadius = 3;
    
    self.CodeBtn.backgroundColor = [UIColor whiteColor];
    self.CodeBtn.layer.masksToBounds = YES;
    self.CodeBtn.layer.cornerRadius = 6;
    [self.CodeBtn setTitleColor:login_BackgroundColor forState:UIControlStateNormal];
    self.CodeBtn.layer.borderWidth = 0.5;
    self.CodeBtn.layer.borderColor = [login_BackgroundColor CGColor];
    
    if (SCREEN_WIDTH ==320) {
        self.forgetHight.constant = 80;
        self.marginHeight.constant = SCREEN_HEIGHT * 80.0/kIPHONE6_HEIGHT;
    }
    [self setBackgound];
    // Do any additional setup after loading the view.
    
    
    _topImageView.layer.cornerRadius = 10;
    _topImageView.layer.masksToBounds = YES;
}
/**
 *  设置控件的边框
 */
-(void)setBackgound
{
    
    [self.phoneTextfield addTarget:self action:@selector(validationChanged:) forControlEvents:UIControlEventEditingChanged];
    
    [self.codeTextfield addTarget:self action:@selector(codevalidationChanged:) forControlEvents:UIControlEventEditingChanged];
    
    [UITextField setupColorWith:@[self.phoneTextfield,self.codeTextfield,self.passworldTextfield]];
    
}

/**
 *  当输入验证码变化
 
 *
*/
-(void)codevalidationChanged:(UITextField *)textfied
{
    if (textfied.text.length ==4) {
        [self.passworldTextfield becomeFirstResponder];
        
        //没有手机号
        if (self.phoneTextfield.text.length  == 0 )
        {
            
            [[UIApplication sharedApplication].keyWindow presentSuccessTips:@"手机号码格式不正确"];
            
            return;
            
            
        }
        
        [self validationCode];
        
    }
    
    
}

//当输入手机号码变化
-(void)validationChanged:(UITextField *)textfied
{
    if (textfied.text.length ==11) {
        
        [self.codeTextfield becomeFirstResponder];
        
        
        
        //判断是否已经注册
        [self isAlreadyregister];
        
    }
}
/**
 *  验证短息码是否正确
 */
-(void)validationCode
{
    
    

    NSDictionary *params =@{
                            @"link_phone":self.phoneTextfield.text,
                            @"phone_code":self.codeTextfield.text
                            };
    [DownloadData post:kVerfiCodeIsRight params:params success:^(id json) {
        
        if ([json[@"error_code"] isEqualToString:@"ok"]) {
            
            self.iscode =YES;
            [self presentSuccessTips:@"验证成功！"];
            
        }else if ([json[@"error_code"] isEqualToString:@"00014"]) {
            
            [self presentFailureTips:@"验证不正确！"];
            self.iscode = NO;
            
            
        }else{
            
            self.iscode = NO;
            [self presentFailureTips:[NSString stringWithFormat:@"验证码错误!"]];
            
        }
        
        
    } failure:^(NSError *error) {
        
    }];
}


/**
 *  重置按钮
 *
 */
- (IBAction)resetClick:(id)sender

{
    
    if (self.phoneTextfield.text.length  == 0 )
    {
        
        [[UIApplication sharedApplication].keyWindow presentSuccessTips:@"手机号码格式不正确"];
        
        return;
        
        
    }
    
    if (![YCCommonTool validatePhoneNumber:self.phoneTextfield.text])
    {
        
        [[UIApplication sharedApplication].keyWindow presentSuccessTips:@"手机号码格式不正确"];
        
        return;
    }
    
    if (self.iscode==NO){
        [[UIApplication sharedApplication].keyWindow presentSuccessTips:@"验证码不正确"];
        
        return;
    }
    
    
    
    BOOL b = [YCCommonTool validatePassword:self.passworldTextfield.text];
 
    if (b == NO){
        [[UIApplication sharedApplication].keyWindow presentSuccessTips:@"密码格式不正确"];
        return;
    }
    
    
    //判断注册还是重置密码
    if (self.isregist) {
        [ self resetPassWord];
        
    }else{
        
        [self registaAccount];
    }
}

//重密码网路请求
-(void)resetPassWord
{
    [[UIApplication sharedApplication].keyWindow presentLoadingTips:nil];

    NSDictionary *params =@{
                            @"link_phone":self.phoneTextfield.text,
                            @"expert_pwd":self.passworldTextfield.text
                            };
    [DownloadData post:kResetVifiCode params:params success:^(id json) {
        
        [[UIApplication sharedApplication].keyWindow dismissTips];
        
        if ([json[@"error_code"] isEqualToString:@"ok"]) {
            
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            
            [def setObject:self.phoneTextfield.text forKey:@"link_mobile"];
            
            [def synchronize];
            
            
            [self dismissViewControllerAnimated:YES completion:^{
                
                [[UIApplication sharedApplication].keyWindow  presentSuccessTips:@"重置成功！"];
                
            }];
            
        }else{
            [[UIApplication sharedApplication].keyWindow presentFailureTips:[NSString stringWithFormat:@"重置失败!"]];
        }
        
    } failure:^(NSError *error) {
        [[UIApplication sharedApplication].keyWindow dismissTips];
        [[UIApplication sharedApplication].keyWindow presentFailureTips:@"重置失败！" ];
    }];
}


- (IBAction)backClick:(id)sender{
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}
- (IBAction)codeClick:(id)sender{
    if (![YCCommonTool validatePhoneNumber:self.phoneTextfield.text]) {
        
        [self presentFailureTips:@"手机格式不对"];
        
        return ;
        
    }
    
    [self validationWithCode];
    _timeTick = 61;
    self.timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
    self.CodeBtn.enabled = NO;
    
}
/**
 *  发送验证码
 */
-(void)validationWithCode
{
    NSDictionary *params =@{
                            @"link_phone":self.phoneTextfield.text,
                            @"sms_type":self.codeType,
                            @"client_id":@"14",
                            @"post_ip":@"192.168.141.219"
                            };
    
    
    [DownloadData post:kGetNewCode params:params success:^(id json) {
        
        NSLog(@"验证码是:%@",json[@"Msg"]);
        
        if ([json[@"Code"] isEqualToString:@"9000"]){
            [self presentSuccessTips:@"已发送！"];
            
        }
        
        if([json[@"Code"] isEqualToString:@"9004"]){
            
            [self presentFailureTips:@"你的语音短信过期了！"];
            
        }
        if([json[@"Code"] isEqualToString:@"9001"]){
            
            [self presentFailureTips:@"短信通道出错！"];
            
        }
    } failure: ^(NSError *error) {
        
    }];
}
/**
 *  60秒倒计时
 */
-(void)timeFireMethod
{
    _timeTick--;
    if(_timeTick==0){
        [self.timer invalidate];
        self.CodeBtn.enabled = YES;
        if (!self.swithType) {
            
            self.codeType = @"1";
            self.swithType =YES;
            
            
            [self.CodeBtn setTitle:@"获取语音验证码" forState:UIControlStateNormal];
            
            
        }else{
            self.codeType = @"0";
            
            self.swithType =NO;
            
            [self.CodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        }
        
    }else
    {
        NSString *str = [NSString stringWithFormat:@"%d秒",_timeTick];
        [self.CodeBtn setTitle:str forState:UIControlStateNormal];
        if (_timeTick ==0) {
            [self.timer invalidate];
            self.CodeBtn.enabled = YES;
            
            if (!self.swithType) {
                
                self.codeType = @"1";
                self.swithType =YES;
                
                [self.CodeBtn setTitle:@"获取语音验证码" forState:UIControlStateNormal];
                
                
            }else{
                self.codeType = @"0";
                self.swithType =NO;
                
                
                [self.CodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
            }
        }
        
    }
    
}
//是否已经注册过
-(void)isAlreadyregister
{

    
    NSDictionary *params =@{
                            @"link_phone":self.phoneTextfield.text,
                            @"yw_id":yw_id
                            
                            };
    [DownloadData post:kIsRegister params:params success:^(id json) {
        //用户多次变幻手机获取短息
        
        self.iscode = NO;
        if (![json[@"expert_id"] isEqualToString:@""]) {
            [self.submitBtn setTitle:@"重置" forState:UIControlStateNormal];
            //已经注册
            self.isregist = YES;
            
            
            
        }else {
            [self.submitBtn setTitle:@"注册" forState:UIControlStateNormal];
        }
        
        
    } failure:^(NSError *error) {
        
    }];
    
}
-(void)registaAccount
{
    
    [[UIApplication sharedApplication].keyWindow  presentLoadingTips:nil];
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString * latitude =[userDefaults valueForKey:@"latitude"];
    NSString * longitude =[userDefaults valueForKey:@"longitude"];
    
    if (!latitude) {
        
        latitude =@"";
        longitude =@"";
    }
    
    
    //    1. 会员注册
    NSDictionary *params =@{
                            @"link_phone":self.phoneTextfield.text,
                            @"expert_pwd":self.passworldTextfield.text,
                            @"expert_name":self.phoneTextfield.text,
                            @"phone_code" :self.codeTextfield.text,
                            @"phoneid" :[[STISystemInfo deviceUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""],
                            @"lat_point" :latitude,
                            @"lng_point" :longitude,
                            @"yw_id":yw_id
                            };
    
    [DownloadData post:kVipRegister params:params success:^(id json) {
        [[UIApplication sharedApplication].keyWindow  dismissTips];
        [[UIApplication sharedApplication].keyWindow  presentFailureTips:@"注册成功！！"];

        
         NSString *expert_id  = json[@"expert_id"];
        NSString *check_flag = json[@"check_flag"];
        //保存登录手机号
        NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
        
        [def setObject:self.phoneTextfield.text forKey:KLINKMOBILE];
        [def setObject:expert_id forKey:KEXPERTID];
        [def setObject:check_flag forKey:KCHECKFLAG];
        [YCUserTool sharedTools].linkMobile = (self.phoneTextfield.text==nil?@"":self.phoneTextfield.text);
        [YCUserTool sharedTools].expertID = (expert_id==nil?@"":expert_id);
        
        
        //将用户的密码保存
        BOOL ii = [YCSSKeychain saveValue:self.passworldTextfield.text andKey:self.phoneTextfield.text];
        if (ii) {
            NSLog(@"保存成功");
        }

        [def synchronize];
        
//        [self createPopView];
        UIWindow *window= [UIApplication sharedApplication].keyWindow;
        YCTabbarViewController *homeVC = [[YCTabbarViewController alloc]init];
        window.rootViewController = homeVC;
        
    } failure:^(NSError *error) {
        [[UIApplication sharedApplication].keyWindow dismissTips];
        
        [[UIApplication sharedApplication].keyWindow  presentFailureTips:@"注册失败！"];
    }];
    
}

- (void)getExpertInof {
    NSUserDefaults *df=  [NSUserDefaults standardUserDefaults];
    NSString *expert_id= [df objectForKey:@"expert_id"];
    
    if (expert_id.length==0) {
        expert_id =@"";
    }
    
    NSDictionary  *params = @{
                              
                              @"expert_id":expert_id
                              
                              };
    
    [DownloadData post:kExpertInfo params:params success:^(id json) {
        
        [self saveNsUserDefaultsDataWithNSDictionary:json];
        
    } failure:^(NSError *error) {
        
        
    }];
}
- (void)saveNsUserDefaultsDataWithNSDictionary:(NSDictionary *)dic
{
    for (int i = 0; i < [dic allValues].count; i ++)
    {
        
        
        if (![[dic allValues][i] isKindOfClass:[NSNull class]])
        {
            NSString * upperkeyStr = [dic allKeys][i];
            
            NSString * lowerCaseStr = [upperkeyStr lowercaseString];
            
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            
            [def setObject:[dic allValues][i] forKey:lowerCaseStr];
            [def synchronize];
            
        }
    }

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}
/** 弹出是的动画，主要改变transform */
- (void)viewShowAnimation {
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    [_popView setTransform:CGAffineTransformScale(transform, 0.3, 0.3)];
    [UIView animateWithDuration:0.2 animations:^{
        [_popView setTransform:CGAffineTransformScale(transform, 1.0, 1.0)];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.2 animations:^{
            [_popView setTransform:CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0)];
        } completion:^(BOOL finished) {
        }];
    }];
}

#pragma mark - popViewDelegate
/** popView的代理方法 */
- (void)popViewClose:(PopView *)popView {
    
    [self closeAnimation];
    UIWindow *window= [UIApplication sharedApplication].keyWindow;
    YCTabbarViewController *homeVC = [[YCTabbarViewController alloc]init];
    window.rootViewController = homeVC;
}

- (void)popViewToApplyView:(PopView *)popView {
    
    ApplyMemberViewController *applyVC = [[ApplyMemberViewController alloc]init];
    
    applyVC.popType = MEMBER_SHIP_POP_TYPE_TAB;
    
    [self presentViewController:applyVC animated:YES completion:nil];
    
}

/** 关闭popView的动画 */
-(void)closeAnimation {
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    [UIView animateWithDuration:0.2 animations:^{
        
        [_popView setTransform:CGAffineTransformScale(transform, 0.05, 0.05)];
    } completion:^(BOOL finished) {
        [self hidenPopView];
    }];
}

/** 将popView remove掉。并且置空。为了重新初始化。 */
- (void)hidenPopView {
    [_popView removeFromSuperview];
    _popView = nil;
}

@end
